/**
 * Created by yuanchao on 2020/6/6.
 */
$(function () {
    //定义相关常量
    //---------------订单类型-------------------------
    var TYPE_IN = "1";        //采购订单
    var TYPE_OUT = "2";       //销售订单

    //---------------采购订单相关状态-------------------
    var STATE_CREATE = "0";   //未审核
    var STATE_CHECK = "1";    //已审核
    var STATE_START = "2";    //已确认
    var STATE_END = "3";      //已入库
    var STATE_NOT_IN = "0";   //未入库
    var STATE_IN = "1";       //已入库

    //---------------销售订单相关状态-------------------
    var STATE_NOT_OUT = "0";  //未出库
    var STATE_OUT = "1";      //已出库

    var url = 'orders_listByPage';
    var btnText = '';
    var inoutTitle = '';
    var isPurchaseOrder = Request['type'] == TYPE_IN;   //type=1 采购单
    var isSellOrder = Request['type'] == TYPE_OUT;      //type=2 销售单

    if (Request['oper'] === 'myorders') {
        if (isPurchaseOrder) {
            url = 'orders_myListByPage?t1.type=1&t1.state=0';      //我的采购订单(t1.state=0表未审核)
            document.title = '我的采购订单';
            btnText = '采购申请';
            inoutTitle = '入库';
            $('#addOrdersSupplier').html('供应商');
        }
        if (isSellOrder) {
            url = 'orders_myListByPage?t1.type=2&t1.state=0';      //我的销售订单(t1.state=0表未出库)
            document.title = '我的销售订单';
            btnText = '销售订单录入';
            inoutTitle = '出库';
            $('#addOrdersSupplier').html('客户');
        }
    } else if (Request['oper'] === 'orders') {
        if (isPurchaseOrder) {                       //采购订单查询
            url += '?t1.type=1';
            document.title = '采购订单查询';
        }
        if (isSellOrder) {                           //销售订单查询
            url += '?t1.type=2';
            document.title = '销售订单查询';
        }
    } else if (Request['oper'] === 'doCheck') {      //审核业务，state=0,只查询出未审核的订单
        url += '?t1.type=1&t1.state=0';
        document.title = '采购订单审核';
    } else if (Request['oper'] === 'doStart') {      //确认业务, state=1,只查询出已审核订单
        url += '?t1.type=1&t1.state=1';
        document.title = '采购订单确认';
    } else if (Request['oper'] === 'doInStore') {    //入库业务，state=2, 只查询出已确认订单
        url += '?t1.type=1&t1.state=2';
        document.title = '采购订单入库';
        inoutTitle = '入库';
    } else if (Request['oper'] === 'doOutStore') {   //出库业务，t1.type=2(销售单), 且 t1.state=0(未出库)
        url += '?t1.type=2&t1.state=0';
        document.title = '销售订单出库';
        inoutTitle = '出库';
    }

    //订单列表
    $('#grid').datagrid({
        url: url,
        singleSelect: true,
        fitColumns: true,
        pagination: true,
        // striped: true,
        columns: getColumns(),
        onDblClickRow: function (rowIndex, rowData) {
            //显示详情
            $('#uuid').html(rowData.uuid);
            $('#waybillsn').html(rowData.waybillsn);
            $('#suppliername').html(rowData.supplierName);
            $('#state').html(getState(rowData.state));
            $('#creater').html(rowData.createrName);
            $('#checker').html(rowData.checkerName);
            $('#starter').html(rowData.starterName);
            $('#ender').html(rowData.enderName);
            $('#createtime').html(formatDate(rowData.createtime));
            $('#checktime').html(formatDate(rowData.checktime));
            $('#starttime').html(formatDate(rowData.starttime));
            $('#endtime').html(formatDate(rowData.endtime));

            //加载明细列表
            $('#itemgrid').datagrid('loadData', rowData.orderDetails);

            //销售单、已出库，显示运单详情按钮
            if (rowData.type === TYPE_OUT && rowData.state === STATE_OUT) {
                showWaybill();
            } else {
                //打开订单详情
                $('#ordersDlg').dialog('open');
            }
        }
    })

    //订单明细列表
    $('#itemgrid').datagrid({
        fitColumns: true,
        singleSelect: true,
        columns: [[
            {field: 'uuid', title: '编号', width: 100},
            {field: 'goodsuuid', title: '商品编号', width: 100},
            {field: 'goodsname', title: '商品名称', width: 100},
            {field: 'price', title: '价格', width: 100},
            {field: 'num', title: '数量', width: 100},
            {field: 'money', title: '金额', width: 100},
            {field: 'state', title: '状态', width: 100, formatter: getDetailState}
        ]]
    });

    //订单详情工具栏
    var toolbar = [];
    if (Request['oper'] === 'doCheck') {
        toolbar.push({
            text: '审核',
            iconCls: 'icon-search',
            handler: doCheck
        });
    } else if (Request['oper'] === 'doStart') {
        toolbar.push({
            text: '确认',
            iconCls: 'icon-search',
            handler: doStart
        });
    } else if (Request['oper'] === 'doInStore' || Request['oper'] === 'doOutStore') {
        $('#itemgrid').datagrid({
            onDblClickRow: function (rowIndex, rowData) {
                //显示数据
                $('#itemuuid').val(rowData.uuid);
                $('#goodsuuid').html(rowData.goodsuuid);
                $('#goodsname').html(rowData.goodsname);
                $('#goodsnum').html(rowData.num);

                //如果已入/出库，则变为只读,且隐藏按钮
                var state = rowData.state;
                var finishState = isPurchaseOrder ? STATE_IN : STATE_OUT;
                if (state === finishState) {
                    $('[name=storeuuid]').parent().css('display', 'none');
                    $('#storename').css('display', '');
                    showOrHideButton(false);
                    getStoreName(rowData.uuid, $('#storename'));
                } else {
                    $('[name=storeuuid]').parent().css('display', '');
                    $('#storename').css('display', 'none');
                    showOrHideButton(true);
                }

                //打开入库/出库窗口
                $('#itemDlg').dialog('open');
            }
        });
    } else if (Request['oper'] === 'myorders') {
        $('#grid').datagrid({
            toolbar: [{
                text: btnText,
                iconCls: 'icon-add',
                handler: function () {
                    $('#addOrdersDlg').dialog('open')
                }
            }]
        });
    }

    //默认都有导出按钮
    toolbar.push({
        text: '导出',
        iconCls: 'icon-excel',
        handler: doExport
    });
    $('#ordersDlg').dialog({toolbar: toolbar});


    //新增订单窗口
    $('#addOrdersDlg').dialog({
        title: '新增订单',
        width: 700,
        height: 400,
        modal: true,
        closed: true
    })


    initInOutStoreDialog();


    /**
     * 根据订单明细id查询所入的仓库
     * @param orderDetailUuid
     */
    function getStoreName(orderDetailUuid, jqueryDom) {
        $.ajax({
            url: 'orderdetail_getStoreByID?id=' + orderDetailUuid,
            type: 'post',
            dataType: 'json',
            success: function (result) {
                if (result.success) {
                    var name = result.data.name || "";
                    jqueryDom.val(name);
                } else {
                    $.messager.alert("提示", result.message, 'info', null);
                }
            }
        })
    }


    /**
     * //初始化入库/出库弹框
     */
    function initInOutStoreDialog() {
        $('#itemDlg').dialog({
            width: 300,
            height: 200,
            title: inoutTitle,
            modal: true,
            closed: true
        });
    }


    /**
     * 显示/隐藏入库/出库按钮
     * @param hasButtons
     */
    function showOrHideButton(hasButtons) {
        if (hasButtons) {
            $('#itemDlg').dialog({
                height: 200,
                buttons: [
                    {
                        text: inoutTitle,
                        iconCls: 'icon-save',
                        handler: function () {
                            if (isPurchaseOrder) {
                                doInStore();
                            } else {
                                doOutStore();
                            }
                        }
                    }
                ]
            })
        } else {
            $('#itemDlg').dialog({
                height: 150,
                buttons: null
            })
        }
    }


    /**
     * 格式化日期
     * @param value
     */
    function formatDate(value) {
        return new Date(value).Format('yyyy-MM-dd')
    }


    /**
     * 获取订单状态
     * 采购：0-未审核，1-已审核，2-已确认，3-已入库
     * @param value
     * @returns {*}
     */
    function getState(value) {
        if (isPurchaseOrder) {
            switch (value * 1) {
                case 0:
                    return '未审核';
                case 1:
                    return '已审核';
                case 2:
                    return '已确认';
                case 3:
                    return '已入库';
                default:
                    return ''
            }
        }
        if (isSellOrder) {
            switch (value * 1) {
                case 0:
                    return '未出库';
                case 1:
                    return '已出库';
                default:
                    return '';
            }
        }
    }


    /**
     * 获取订单明细的状态
     * 采购单：0-未入库， 1-已入库
     * 销售单：0-未出库，1-已出库
     * @param value
     */
    function getDetailState(value) {
        if (isPurchaseOrder) {
            switch (value * 1) {
                case 0:
                    return '未入库';
                case 1:
                    return '已入库';
                default:
                    return ''
            }
        }
        if (isSellOrder) {
            switch (value * 1) {
                case 0:
                    return '未出库';
                case 1:
                    return '已出库';
                default:
                    return ''
            }
        }
    }

    /**
     * 订单审核
     */
    function doCheck() {
        $.messager.confirm("提示", "确认要审核吗?", function (yes) {
            if (yes) {
                $.ajax({
                    url: 'orders_doCheck?id=' + $('#uuid').html(),
                    type: 'post',
                    dataType: 'json',
                    success: function (result) {
                        if (result.success) {
                            //关闭订单详情对话框
                            $('#ordersDlg').dialog('close');
                            //刷新订单列表
                            $('#grid').datagrid('reload');
                        } else {
                            $.messager.alert('提示', result.message, 'info', function () {
                                if (result.message === '请先登录!') {
                                    window.location.href = 'login.html';
                                }
                            })
                        }
                    }
                });
            }
        })
    }

    /**
     * 订单确认
     */
    function doStart() {
        $.messager.confirm("提示", "确认要确认吗?", function (yes) {
            if (yes) {
                $.ajax({
                    url: 'orders_doStart?id=' + $('#uuid').html(),
                    type: 'post',
                    dataType: 'json',
                    success: function (result) {
                        if (result.success) {
                            //关闭订单详情对话框
                            $('#ordersDlg').dialog('close');
                            //刷新订单列表
                            $('#grid').datagrid('reload');
                        } else {
                            $.messager.alert('提示', result.message, 'info', function () {
                                if (result.message === '请先登录!') {
                                    window.location.href = 'login.html';
                                }
                            })
                        }
                    }
                });
            }
        })
    }


    /**
     * 订单明细入库(采购单)
     */
    function doInStore() {
        var formData = $('#itemForm').serializeJSON();
        if (!formData.storeuuid) {
            $.messager.alert('提示', '请选择仓库', 'info');
            return;
        }
        $.messager.confirm("提示", "确认要入库吗?", function (yes) {
            if (yes) {
                $.ajax({
                    url: 'orderdetail_doInStore',
                    type: 'post',
                    data: formData,
                    dataType: 'json',
                    success: function (result) {
                        if (result.success) {
                            //关闭入库窗口
                            $('#itemDlg').dialog('close');

                            //刷新订单明细列表
                            var row = $('#itemgrid').datagrid('getSelected');   //获取当前操作的行
                            row.state = '1';                                    //修改其状态为已入库1
                            var data = $('#itemgrid').datagrid('getData');      //典型的刷新datagrid的技巧
                            $('#itemgrid').datagrid('loadData', data);

                            //如果所有明细均已入库，关闭订单详情窗口，并且刷新订单列表
                            var allIn = true;
                            $.each(data.rows, function (i, row) {
                                if (row.state * 1 === 0) {
                                    allIn = false;
                                    //跳出循环
                                    return false
                                }
                            })
                            if (allIn) {
                                $('#ordersDlg').dialog('close');
                                $('#grid').datagrid('reload');
                            }
                        } else {
                            $.messager.alert('提示', result.message, 'info', function () {
                                if (result.message === '请先登录!') {
                                    window.location.href = 'login.html';
                                }
                            })
                        }
                    }
                });
            }
        })
    }


    /**
     * 订单明细出库(销售单)
     */
    function doOutStore() {
        var formData = $('#itemForm').serializeJSON();
        if (!formData.storeuuid) {
            $.messager.alert('提示', '请选择仓库', 'info');
            return;
        }
        $.messager.confirm("提示", "确认要出库吗?", function (yes) {
            if (yes) {
                $.ajax({
                    url: 'orderdetail_doOutStore',
                    type: 'post',
                    data: formData,
                    dataType: 'json',
                    success: function (result) {
                        if (result.success) {
                            //关闭出库窗口
                            $('#itemDlg').dialog('close');

                            //刷新订单明细列表
                            var row = $('#itemgrid').datagrid('getSelected');   //获取当前操作的行
                            row.state = '1';                                    //修改其状态为已出库1
                            var data = $('#itemgrid').datagrid('getData');      //典型的刷新datagrid的技巧
                            $('#itemgrid').datagrid('loadData', data);

                            //如果所有明细均已出库，关闭订单详情窗口，并且刷新订单列表
                            var allOut = true;
                            $.each(data.rows, function (i, row) {
                                if (row.state * 1 === 0) {
                                    allOut = false;
                                    //跳出循环
                                    return false
                                }
                            })
                            if (allOut) {
                                $('#ordersDlg').dialog('close');
                                $('#grid').datagrid('reload');
                            }
                        } else {
                            $.messager.alert('提示', result.message, 'info', function () {
                                if (result.message === '请先登录!') {
                                    window.location.href = 'login.html';
                                }
                            })
                        }
                    }
                });
            }
        })
    }


    /**
     * 获取订单列表的显示字段,采购单和销售单显示的字段有所不同
     * @returns {*}
     */
    function getColumns() {
        var columns = null;
        if (isPurchaseOrder) {
            columns = [[
                {field: 'uuid', title: '编号', width: 100},
                {field: 'createtime', title: '生成日期', width: 100, formatter: formatDate},
                {field: 'checktime', title: '审核日期', width: 100, formatter: formatDate},
                {field: 'starttime', title: '确认日期', width: 100, formatter: formatDate},
                {field: 'endtime', title: '入库日期', width: 100, formatter: formatDate},
                {field: 'createrName', title: '下单员', width: 100},
                {field: 'checkerName', title: '审核员', width: 100},
                {field: 'starterName', title: '采购员', width: 100},
                {field: 'enderName', title: '库管员', width: 100},
                {field: 'supplierName', title: '供应商', width: 100},
                {field: 'totalmoney', title: '合计金额', width: 100},
                {field: 'state', title: '状态', width: 100, formatter: getState},
                {field: 'waybillsn', title: '运单号', width: 100}
            ]];
        } else {
            columns = [[
                {field: 'uuid', title: '编号', width: 100},
                {field: 'createtime', title: '生成日期', width: 100, formatter: formatDate},
                {field: 'endtime', title: '出库日期', width: 100, formatter: formatDate},
                {field: 'createrName', title: '下单员', width: 100},
                {field: 'enderName', title: '库管员', width: 100},
                {field: 'supplierName', title: '客户', width: 100},
                {field: 'totalmoney', title: '合计金额', width: 100},
                {field: 'state', title: '状态', width: 100, formatter: getState},
                {field: 'waybillsn', title: '运单号', width: 100}
            ]];
        }
        return columns;
    }


    /**
     * 执行导出功能
     */
    function doExport() {
        // $.download("orders_export", {"id": $('#uuid').html()});
        $.download("orders_exportByTemplate", {"id": $('#uuid').html()});
    }


    function showWaybill() {
        var options = $('#ordersDlg').dialog('options');
        var toolbar = options.toolbar;
        toolbar.push({
            text: '运单详情',
            iconCls: 'icon-search',
            handler: function () {
                $.ajax({
                    url: 'orders_waybilldetailList?waybillsn=' + $("#waybillsn").html(),
                    type: 'post',
                    dataType: 'json',
                    success: function (result) {
                        if (result.success) {
                            var data = result.data || [];
                            $('#waybillDlg').dialog('open');
                            $('#waybillGrid').datagrid({
                                singleSelect: true,
                                fitColumns: true,
                                rownumbers: true,
                                data: data,
                                columns: [[
                                    {field: 'exedate', title: '执行日期', width: 100},
                                    {field: 'exetime', title: '执行时间', width: 100},
                                    {field: 'info', title: '执行信息', width: 100}
                                ]]
                            })
                        } else {
                            $.messager.alert('提示', result.message, 'info', null);
                        }
                    }
                });
            }
        })
        //重新渲染订单详情对话框
        $('#ordersDlg').dialog({
            toolbar: toolbar,
            onClose: function () {
                //每次关闭前删除运单详情按钮，保证界面上只出现一个运单详情按钮
                toolbar.pop();
                $('#ordersDlg').dialog({toolbar: toolbar, onClose: null});
                //重置运单号
                $('#waybillsn').html('');
            }
        })
        //打开订单详情
        $('#ordersDlg').dialog('open');
    }
})